/**
 * Created by Pup on 2017/10/15.
 */

// for csrf
// using jQuery  手动获取csrf的值，post时还需设置进去
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}

// end csrf

// send msg
$(document).ready(function () {
    // set csrf before send ajax
    $.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });
    // end set csrf

    // 定时获取消息
    var MsgRefresher = setInterval(function () {
        GetNewMsgs();
    }, 5000);
    // end获取消息

    $('body').delegate('textarea', 'keydown',function(e) {
        if (e.which == 13) {// Enter key down
            // send msg button clicked
            var msg_text = $('.chat-box-msg-box textarea').val();
            if ($.trim(msg_text).length > 0) {
                // console.log(msg_text);
                SendMsg(msg_text);
            }// end if
            // no wait the send_msg's call confirm msg
            AddSentMsgIntoBox(msg_text);
            $('.chat-box-msg-box textarea').val('');
        }// end if
    });
});


function SendMsg(msg_text) {
    var contact_type = $('.chat-box-title').attr('contact-type');
    var contact_id = $('.chat-box-title').attr('contact-id');
    if(contact_type && contact_id){
        var msg_item = {
            'from': '{{ request.user.userprofile.id }}',
            'to': contact_id,
            'type': contact_type,
            'msg': msg_text
        };
        $.post('/send_msg', {data: JSON.stringify(msg_item)}, function (callback) {
            console.log(callback);
        })
    }// end if

}


function AddSentMsgIntoBox(msg_text) {
    var new_msg_ele = '<div class="msg-item">' +
            '<span>' + '{{ request.User.userprofile.name }}' + '</span>' +
            '<span>' + new Date().toLocaleTimeString() + '</span>' +
            '<div class="msg-text">' + msg_text + '</div>' +
            '</div>' + '<br/>';
    $('.chat-box-window').append(new_msg_ele);

    $('.chat-box-window').animate({
        scrollTop: $('.chat-box-window')[0].scrollHeight
    }, 500);

}


function OpenChatWindow(ths) {
    $(ths).addClass('active');
    $(ths).siblings().removeClass('active');
    var contact_id = $(ths).attr('contact-id');
    var contact_type = $(ths).attr('contact-type');
    var contact_name = $(ths).find('.contact-name').text();

    var chat_box_title_content = '正在跟 ' + contact_name + ' 聊天';
    $('.chat-box-title').html(chat_box_title_content);
    $('.chat-box-title').attr('contact-id', contact_id);
    $('.chat-box-title').attr('contact-type', contact_type);
}

function GetNewMsgs() {
    $.getJSON('/new_msgs', function (callback) {
        console.log(callback);
    });// end post

}